package service

import (
	"devops/middleware"
	"devops/models"
	"errors"
)

func (d *devOps) CreateProject(name string, uid int, description string, icon string) error {
	// 先查询是否存在
	project := models.GetProject(models.Project{Name: name})
	if project.ID != 0 {
		return errors.New("项目已存在")
	}
	// 请求 jenkins api 创建
	_, err := d.CreateFolder(name)
	if err != nil {
		return err
	}
	// 同步数据库
	models.CreateProject(models.Project{
		Name:        name,
		Description: description,
		Icon:        icon,
		Uid:         uid,
	})
	return nil
}

func (d *devOps) GetAllProject() []*models.Project {
	return models.GetAllProject()
}

func (d *devOps) GetProjectDashboard() []*models.ProjectDashboard {
	projects := d.GetAllProject()
	dashboard := make([]*models.ProjectDashboard, 0, len(projects))

	for _, project := range projects {
		cis := models.GetProjectCI(project.ID)
		count := models.CiCount{Total: len(cis)}
		for _, ci := range cis {
			lastBuild := models.GetCILastBuild(ci.ID)
			// 指针为空代表没有构建计划
			if lastBuild == nil {
				count.NotBuild++
				continue
			}
			// 统计结果
			switch lastBuild.Result {
			case "UNKNOWN":
				count.Running++
			case "SUCCESS":
				count.Success++
			case "FA":
				count.Failure++
			default:
				count.Other++
			}
		}
		dashboard = append(dashboard, &models.ProjectDashboard{*project, count})
	}
	return dashboard
}

func (d *devOps) GetBuildDashboard(start, end, page, pageSize int) ([]models.BuildDashboard, int) {
	builds, total := models.GetBuildPageBetweenTime(start, end, page, pageSize)
	dashboard := make([]models.BuildDashboard, 0, len(builds))
	for _, b := range builds {
		ci := models.GetCIByID(b.CID)
		project := models.GetProjectByID(ci.ProjectId)
		dashboard = append(dashboard, models.BuildDashboard{
			CID:       b.CID,
			CName:     ci.Name,
			PID:       ci.ProjectId,
			PName:     project.Name,
			BuildID:   b.ID,
			Result:    b.Result,
			StartUser: b.StartUser,
			BuildType: b.Type,
			StartTime: b.CreatedAt,
			Duration:  b.Duration,
		})
	}
	return dashboard, total
}

func (d *devOps) DeleteProject(id int, user middleware.User) error {
	project := models.GetProjectByID(id)
	if project.ID == 0 {
		return nil
	}
	err := d.DeleteFolder(project.Name)
	if err != nil {
		return err
	}
	models.DeleteProject(id)

	// 记录事件
	go d.ProjectEvent(ProjectDelete, &user, project)
	return nil
}
